//共同使用的方法集合

import { customRef } from 'vue';
import { ElLoading, ElMessage } from 'element-plus';

// 开启服务loading
const openLoading = (text = '加载中...') => {
  const option = {
    lock: true,
    text: text,
    background: 'rgba(0, 0, 0, 0.7)'
  };
  const loadingInstance = ElLoading.service(option);
  return loadingInstance;
};
// 关闭服务loading
const closeLoading = () => {
  openLoading().close();
};

//js防抖测试
const testDebounce = (func, wait = 1000) => {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.call(this, ...args);
    }, wait);
  };
};

// vue3自定义ref防抖
const debounceRef = (value, delay = 800) => {
  let timer;
  return customRef((track, trigger) => {
    return {
      get() {
        // 依赖收集
        track();
        return value;
      },
      set(val) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          value = val;
          // 派发更新
          trigger();
        }, delay);
      }
    };
  });
};

// // vue3自定义ref防抖
// const debounceRef = (value, delay = 200, fn) => {
//   var timer
//   return customRef((track, trigger) => {
//     return {
//       get() {
//         // console.log(  `---有人从容器myRef读取myKeword了--- 我把${value}给了他` // )
//         track() // 告诉vue value 这个值需要追踪
//         return value
//       },
//       set(newValue) {
//         clearTimeout(timer)
//         timer = setTimeout(() => {
//           fn()
//           // console.log(`---有人从容器myRef读取修改myKeword为${newValue}`)
//           value = newValue // 修改value 这个值
//           trigger() // 告诉vue重新去解析模板
//         }, delay)
//       },
//     }
//   })
// }

// message消息提醒
const myMessage = (msg = '操作成功！', type = 'success') => {
  ElMessage({
    message: msg,
    type: type
  });
};

// 深度克隆对象
const deepClone = (obj) => {
  return new Promise((resolve, reject) => {
    try {
      // 创建两端
      const { port1, port2 } = new MessageChannel();
      port1.postMessage(obj);
      port2.onmessage = (msg) => {
        resolve(msg.data);
      };
    } catch (error) {
      reject(error);
    }
  });
};
export { debounceRef, testDebounce, closeLoading, openLoading, myMessage, deepClone };
